/* eslint-disable @typescript-eslint/no-unused-vars */
'use client'

import { useState, useRef, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Loader2, Copy, Download } from 'lucide-react'
import { toast } from 'sonner'
import { presetTemplates, type } from '@/lib/constants'
import PresetTemplateGrid from './PresetTemplateGrid'
import bgi from '../lib/bgi.json'
import { Language, translations } from '@/lib/i18n'

interface Props {
  base64Image: string
  lang: Language
}

export default function SvgGenerator({ base64Image, lang }: Props) {
  const t = translations[lang]
  const [text, setText] = useState('')
  const [cueWord, setCueWord] = useState(0)
  const [svg, setSvg] = useState('')
  const [loading, setLoading] = useState(false)
  const svgRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    localStorage.setItem('cueWord', String(cueWord))
  }, [cueWord])

  function modifySvg(svgString: string, bgiSrc: string) {
    const img = `<image  href="${bgiSrc}" width="100%" height="100%" />`
    const regex = /<rect[^>]*>/
    const match = svgString.match(regex)

    if (match && match.length > 0) {
      const firstRect = match[0]
      const modifiedSvgString = svgString.replace(
        firstRect,
        `${firstRect} \n ${img}`,
      )
      return modifiedSvgString
    }
    return svgString
  }

  const onSubmit = async () => {
    if (!text) {
      toast.error(lang === 'zh-CN' ? '请输入内容' : 'Please enter content')
      return
    }
    setLoading(true)
    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ prompt: text, word: cueWord }),
      })

      const data = await response.json()

      if (data.svgContent) {
        setSvg(modifySvg(data.svgContent, base64Image || bgi.src))
        toast.success(
          lang === 'zh-CN' ? 'SVG 生成成功' : 'SVG generated successfully',
        )
      } else {
        toast.error(lang === 'zh-CN' ? '无法生成 SVG' : 'Failed to generate SVG')
      }
    } catch (error) {
      console.error('Error:', error)
      toast.error(
        lang === 'zh-CN' ? '生成过程中出现错误' : 'Error occurred during generation',
      )
    } finally {
      setLoading(false)
    }
  }

  const downloadImage = () => {
    if (!svgRef.current) return

    const svgElement = svgRef.current.querySelector('svg')
    if (!svgElement) {
      toast.error(lang === 'zh-CN' ? 'SVG 元素未找到' : 'SVG element not found')
      return
    }

    // 获取原始SVG的尺寸和viewBox
    const svgWidth = svgElement.getAttribute('width')
    const svgHeight = svgElement.getAttribute('height')
    const viewBox = svgElement.getAttribute('viewBox')

    // 设置更高的分辨率
    const scale = 4
    const width = parseInt(svgWidth || '800')
    const height = parseInt(svgHeight || '600')

    // 创建一个新的SVG元素，保留原始尺寸和viewBox
    const newSvg = svgElement.cloneNode(true) as SVGElement
    newSvg.setAttribute('width', width.toString())
    newSvg.setAttribute('height', height.toString())
    if (viewBox) newSvg.setAttribute('viewBox', viewBox)

    const svgData = new XMLSerializer().serializeToString(newSvg)
    const svgBlob = new Blob([svgData], {
      type: 'image/svg+xml;charset=utf-8',
    })
    const svgUrl = URL.createObjectURL(svgBlob)

    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = width * scale
      canvas.height = height * scale
      const ctx = canvas.getContext('2d')

      if (ctx) {
        ctx.imageSmoothingEnabled = false
        ctx.drawImage(img, 0, 0, width * scale, height * scale)

        canvas.toBlob(
          (blob) => {
            if (!blob) {
              toast.error('无法创建图片')
              return
            }
            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            a.download = 'generated.png'
            a.click()
            URL.revokeObjectURL(url)
            URL.revokeObjectURL(svgUrl)
          },
          'image/png',
          1.0,
        )
      }
    }

    img.src = svgUrl
  }

  const copyImageToClipboard = async () => {
    if (!svgRef.current) return

    try {
      const svgElement = svgRef.current.querySelector('svg')
      if (!svgElement) throw new Error('SVG element not found')

      // 获取原始SVG的尺寸和viewBox
      const svgWidth = svgElement.getAttribute('width')
      const svgHeight = svgElement.getAttribute('height')
      const viewBox = svgElement.getAttribute('viewBox')

      // 设置更高的分辨率
      const scale = 4
      const width = parseInt(svgWidth || '800')
      const height = parseInt(svgHeight || '600')

      // 创建一个新的SVG元素，保留原始尺寸和viewBox
      const newSvg = svgElement.cloneNode(true) as SVGElement
      newSvg.setAttribute('width', width.toString())
      newSvg.setAttribute('height', height.toString())
      if (viewBox) newSvg.setAttribute('viewBox', viewBox)

      const svgData = new XMLSerializer().serializeToString(newSvg)
      const svgBlob = new Blob([svgData], {
        type: 'image/svg+xml;charset=utf-8',
      })
      const svgUrl = URL.createObjectURL(svgBlob)

      const img = new Image()
      img.onload = async () => {
        const canvas = document.createElement('canvas')
        canvas.width = width * scale
        canvas.height = height * scale
        const ctx = canvas.getContext('2d')
        if (!ctx) throw new Error('Unable to create canvas context')

        ctx.imageSmoothingEnabled = false
        ctx.drawImage(img, 0, 0, width * scale, height * scale)

        try {
          const blob = await new Promise<Blob>((resolve) =>
            canvas.toBlob(resolve as BlobCallback, 'image/png', 1.0),
          )
          await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
          toast.success(
            lang === 'zh-CN'
              ? '高清图片已复制到剪贴板'
              : 'HD image copied to clipboard',
          )
        } catch (err) {
          console.error(err)
          toast.error(lang === 'zh-CN' ? '复制图片失败' : 'Failed to copy image')
        } finally {
          URL.revokeObjectURL(svgUrl)
        }
      }

      img.src = svgUrl
    } catch (error) {
      console.error('Error:', error)
      toast.error(lang === 'zh-CN' ? '复制图片失败' : 'Failed to copy image')
    }
  }

  const handleTemplateSelect = (template: { prompt: string; svg: string }) => {
    setText(template.prompt)
    setSvg(template.svg)
    toast.success(lang === 'zh-CN' ? '模板已加载' : 'Template loaded')
  }

  return (
    <div className="md:container p-4 md:p-8 min-h-[63vh]">
      <div className="flex flex-col md:flex-row gap-8">
        <div className="w-full md:w-1/2">
          <Card className="h-full shadow-sm hover:shadow-md transition-shadow duration-300 hover:border-blue-300">
            <CardContent className="space-y-6 p-6">
              <h2 className="text-2xl font-bold mb-4">
                {lang === 'zh-CN'
                  ? '微言威语 | 给汉语一个全新的解释'
                  : 'Micro Expression | A New Interpretation of Chinese'}
              </h2>

              <div className="space-y-2">
                <h3 className="text-sm font-semibold text-gray-600">
                  {lang === 'zh-CN' ? '汉语输入' : 'Chinese Input'}
                </h3>
                <Input
                  type="text"
                  value={text}
                  onChange={(e) => setText(e.target.value)}
                  placeholder={
                    lang === 'zh-CN' ? '输入一个汉语词汇' : 'Enter a Chinese word'
                  }
                  className="text-lg focus:ring-2 focus:ring-blue-200"
                />
              </div>

              <div className="space-y-3">
                <h3 className="text-sm font-semibold text-gray-600">
                  {lang === 'zh-CN' ? '文案类型' : 'Content Type'}
                </h3>
                <div className="flex flex-wrap gap-2">
                  {type[lang].map((item, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      onClick={() => setCueWord(index)}
                      style={{
                        color: cueWord === index ? '#fff' : '#000',
                        backgroundColor: cueWord === index ? '#3662e3' : '#fff',
                      }}
                      className="text-sm hover:bg-gray-100"
                    >
                      {item}
                    </Button>
                  ))}
                </div>
              </div>

              <div className="space-y-3">
                <h3 className="text-sm font-semibold text-gray-600">
                  {lang === 'zh-CN' ? '推荐词汇' : 'Recommended Words'}
                </h3>
                <div className="flex flex-wrap gap-2">
                  {presetTemplates(base64Image).map((item) => (
                    <Button
                      key={item.prompt}
                      variant="outline"
                      onClick={() => {
                        setText(item.prompt)
                        setSvg(item.svg)
                      }}
                      className="text-sm hover:bg-gray-100"
                    >
                      {item.prompt}
                    </Button>
                  ))}
                </div>
              </div>

              <Button
                onClick={onSubmit}
                className="w-full text-lg bg-blue-600 hover:bg-blue-700 text-white"
                disabled={loading}
              >
                {loading ? (
                  <Loader2 className="animate-spin w-5 h-5 mr-2" />
                ) : lang === 'zh-CN' ? (
                  '生成汉语解释'
                ) : (
                  'Generate Chinese Interpretation'
                )}
              </Button>
            </CardContent>
          </Card>
        </div>

        <div className="w-full md:w-1/2">
          {loading ? (
            <Card className="h-full shadow-sm hover:shadow-md transition-shadow duration-300 hover:border-blue-300 py-8 md:py-10">
              <CardContent className="flex items-center justify-center h-full">
                <div className="animate-pulse flex space-x-4">
                  <div className="rounded-full bg-slate-300 h-10 w-10"></div>
                  <div className="flex-1 space-y-6 py-1">
                    <div className="h-2 bg-slate-300 rounded"></div>
                    <div className="space-y-3">
                      <div className="grid grid-cols-3 gap-4">
                        <div className="h-2 bg-slate-300 rounded col-span-2"></div>
                        <div className="h-2 bg-slate-300 rounded col-span-1"></div>
                      </div>
                      <div className="h-2 bg-slate-300 rounded"></div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          ) : svg ? (
            <Card className="h-full shadow-sm hover:shadow-md transition-shadow duration-300 hover:border-blue-300">
              <CardContent className="p-6 flex flex-col items-center justify-center h-full">
                <div
                  ref={svgRef}
                  dangerouslySetInnerHTML={{ __html: svg }}
                  className="mb-6 w-full h-full"
                />
                <div className="flex gap-2 flex-col md:flex-row">
                  <Button variant="outline" onClick={downloadImage}>
                    <Download className="w-4 h-4 mr-2" />
                    {lang === 'zh-CN' ? '下载图片' : 'Download Image'}
                  </Button>
                  <Button variant="outline" onClick={copyImageToClipboard}>
                    <Copy className="w-4 h-4 mr-2" />
                    {lang === 'zh-CN' ? '复制图片' : 'Copy Image'}
                  </Button>
                  <Button
                    variant="outline"
                    onClick={async () => {
                      await navigator.clipboard.writeText(svg)
                      toast.success(
                        lang === 'zh-CN'
                          ? 'SVG 已复制到剪贴板'
                          : 'SVG copied to clipboard',
                      )
                    }}
                  >
                    <Copy className="w-4 h-4 mr-2" />
                    {lang === 'zh-CN' ? '复制 SVG' : 'Copy SVG'}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            <Card className="h-full py-8 md:py-10">
              <CardContent className="flex items-center justify-center h-full text-gray-500">
                {lang === 'zh-CN'
                  ? '生成的汉语解释将显示在这里'
                  : 'Generated Chinese interpretation will be shown here'}
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      <div className="mt-12">
        <h2 className="text-2xl font-bold mb-6">
          {lang === 'zh-CN' ? '微言威语例子' : 'Micro Expression Examples'}
        </h2>
        <PresetTemplateGrid
          templates={presetTemplates(base64Image)}
          onSelect={handleTemplateSelect}
          lang={lang}
        />
      </div>
    </div>
  )
}
